package com.sdgs.paas.sdk.core.web.client;

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.http.RequestEntity;

import com.sdgs.paas.sdk.core.log.PaasLogger;

/**
 * SDK请求审计切面
 *
 * @author wjj
 *
 */
@Aspect
public class PaasRestTemplateAuditAspect {

	@Pointcut("target(com.sdgs.paas.sdk.core.web.client.PaasRestTemplate)")
	public void executePointCut() {
	}

	@Before("executePointCut()")
	public void checkBefore(JoinPoint jp) {
		StackTraceElement[] stackTrace = new Throwable().getStackTrace();
		List<StackTraceElement> stackLst = Arrays.asList(stackTrace);
		Iterator<StackTraceElement> it = stackLst.stream()
				.filter(e -> e.getClassName().contains("PaasRestTemplate$$EnhancerBySpringCGLIB")).iterator();
		if (it.hasNext()) {
			StackTraceElement pretarget = it.next();
			StackTraceElement target = stackLst.get(stackLst.indexOf(pretarget) + 1);
			Object[] args = jp.getArgs();
			if (args.length > 0) {

				Object arg = jp.getArgs()[0];
				String url = null;
				PaasLogger.debug("PaasRestTemplate访问路径审计记录！classname:{}", arg.getClass().getName());
				switch (arg.getClass().getName()) {
				case "java.lang.String":
					url = (String) arg;
					break;
				case "java.net.URI":
					url = arg.toString();
					break;
				case "org.springframework.http.RequestEntity":
					url = ((RequestEntity<?>) arg).getUrl().toString();
					break;
				default:
					url = "unknown";

				}
				if (!url.equals("unknown")) {
					PaasLogger.info("PaasRestTemplate访问路径审计记录！本次http调用的类名:{},方法名:{},URL:{}", target.getClassName(),
							target.getMethodName(), url);
				}

			}
		}

	}

}